package com.hydra.base.global;

import com.hydra.base.error.BusinessException;
import com.hydra.base.error.ValidateException;
import com.hydra.base.resp.ResultError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局错误处理
 * @Author Hydra
 * @Date 2022/4/18 15:57
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 校验异常
     * 处理运行时系统异常（返回200的状态码，里面再设置400的错误码）
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ValidateException.class)
    public ResultError handleValidateException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("handleValidateException start, uri:{}, exception:{}, caused by: {}", requestURI, e.getClass(), e.getMessage());
        return ResultError.failure(HttpServletResponse.SC_BAD_REQUEST, "Validate Error", e.getMessage(), requestURI);
    }

    /**
     * 业务异常
     * 处理运行时系统异常（返回500的错误码）
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public ResultError handleBusinessException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("handleBusinessException start, uri:{}, exception:{}, caused by: {}", requestURI, e.getClass(), e.getMessage());
        StackTraceElement[] stackTrace = e.getStackTrace();
        if(stackTrace != null && stackTrace.length > 0){
            log.error("caused by: {}, location: {}", e.getMessage(), stackTrace[0].toString());
        }
        return ResultError.failure(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Business Error", e.getMessage(), requestURI);
    }

    /**
     * 500异常时，抛出此异常
     * 处理运行时系统异常（返回500的错误码）
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResultError handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("handleException start, uri:{}, exception:{}, caused by: {}", requestURI, e.getClass(), e.getMessage(), e);
        return ResultError.failure(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error", e.getMessage(), requestURI);
    }

}
